

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Dragonborn-zz">
  <meta name="keywords" content="">
  
    <meta name="description" content="# Retrofit2 文件上传与下载 # 文件上传：(包括多文件上传) # 第一步：创建服务返回数据的 bean 类；(此处服务器返回的是 json 字符串); 12345678public class BaseBean&amp;#123;    private int Code;    private String Msg;    private String Data;    &#x2F;&#x2F;...setget">
<meta property="og:type" content="article">
<meta property="og:title" content="Retrofit2文件上传与下载">
<meta property="og:url" content="http://example.com/2024/02/18/android/Retrofit2%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8E%E4%B8%8B%E8%BD%BD/index.html">
<meta property="og:site_name" content="Dragonborn-zz&#39;s个人博客">
<meta property="og:description" content="# Retrofit2 文件上传与下载 # 文件上传：(包括多文件上传) # 第一步：创建服务返回数据的 bean 类；(此处服务器返回的是 json 字符串); 12345678public class BaseBean&amp;#123;    private int Code;    private String Msg;    private String Data;    &#x2F;&#x2F;...setget">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2024-02-18T03:28:48.555Z">
<meta property="article:modified_time" content="2023-07-29T01:10:02.000Z">
<meta property="article:author" content="Dragonborn-zz">
<meta name="twitter:card" content="summary_large_image">
  
  
  
  <title>Retrofit2文件上传与下载 - Dragonborn-zz&#39;s个人博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.7","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":{"measurement_id":null},"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml","include_content_in_search":true};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Dragonborn-zz</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/" target="_self">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/" target="_self">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/" target="_self">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/" target="_self">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="https://gitee.com/dragonborn-zz" target="_self">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/home.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Retrofit2文件上传与下载"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2024-02-18 03:28" pubdate>
          2024年2月18日 凌晨
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          1.3k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          11 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <h1 id="seo-header">Retrofit2文件上传与下载</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="retrofit2文件上传与下载"><a class="markdownIt-Anchor" href="#retrofit2文件上传与下载">#</a> Retrofit2 文件上传与下载</h1>
<h3 id="文件上传包括多文件上传"><a class="markdownIt-Anchor" href="#文件上传包括多文件上传">#</a> 文件上传：(包括多文件上传)</h3>
<h4 id="第一步创建服务返回数据的bean类此处服务器返回的是json字符串"><a class="markdownIt-Anchor" href="#第一步创建服务返回数据的bean类此处服务器返回的是json字符串">#</a> 第一步：创建服务返回数据的 bean 类；(此处服务器返回的是 json 字符串);</h4>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">BaseBean</span>&#123;<br><br>    <span class="hljs-keyword">private</span> <span class="hljs-type">int</span> Code;<br>    <span class="hljs-keyword">private</span> String Msg;<br>    <span class="hljs-keyword">private</span> String Data;<br>    <span class="hljs-comment">//...setget方法</span><br><br>&#125; <br></code></pre></td></tr></table></figure>
<h4 id="第二步创建用于描述网络请求的接口"><a class="markdownIt-Anchor" href="#第二步创建用于描述网络请求的接口">#</a> 第二步：创建用于描述网络请求的接口</h4>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs dart">public <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Api</span> </span>&#123;<br><span class="hljs-comment"><span class="language-markdown">/**</span></span><br><span class="language-markdown"><span class="hljs-comment"><span class="hljs-bullet">*</span> 上传</span></span><br><span class="language-markdown"><span class="hljs-comment"><span class="hljs-bullet">*</span> Multipart 这个注解代表多表单上传</span></span><br><span class="language-markdown"><span class="hljs-comment"><span class="hljs-bullet">*</span> @param partList 表单信息</span></span><br><span class="language-markdown"><span class="hljs-comment"><span class="hljs-bullet">*</span> @return .</span></span><br><span class="language-markdown"><span class="hljs-comment"><span class="hljs-emphasis">*/</span></span></span><br><span class="hljs-meta">@Multipart</span><br><span class="hljs-meta">@POST</span>(<span class="hljs-string">&quot;服务器地址(就创建retrofit设置的基站地址后面的具体地址)&quot;</span>)<br>Call&lt;BaseBean&gt; upLoading(<span class="hljs-meta">@Part</span> <span class="hljs-built_in">List</span>&lt;MultipartBody.Part&gt; partList);<br><br> &#125; <br></code></pre></td></tr></table></figure>
<h2 id="第三步创建表单里面存储服务器本接口所需要的数据"><a class="markdownIt-Anchor" href="#第三步创建表单里面存储服务器本接口所需要的数据">#</a> 第三步：创建表单，里面存储服务器本接口所需要的数据；</h2>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs cpp">参数添加<br>MultipartBody.Builder builder = <span class="hljs-keyword">new</span> MultipartBody.<span class="hljs-built_in">Builder</span>()<br>           .<span class="hljs-built_in">setType</span>(MultipartBody.FORM)<br>           <span class="hljs-comment">//在这里添加服务器除了文件之外的其他参数</span><br>           .<span class="hljs-built_in">addFormDataPart</span>(<span class="hljs-string">&quot;参数1&quot;</span>, <span class="hljs-string">&quot;值1&quot;</span>)<br>           .<span class="hljs-built_in">addFormDataPart</span>(<span class="hljs-string">&quot;参数2&quot;</span>, <span class="hljs-string">&quot;值2&quot;</span>); <br></code></pre></td></tr></table></figure>
<h5 id="创建文件你需要上传到服务器的文件"><a class="markdownIt-Anchor" href="#创建文件你需要上传到服务器的文件">#</a> 创建文件 (你需要上传到服务器的文件)</h5>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs cpp">File file = <span class="hljs-keyword">new</span> <span class="hljs-built_in">File</span>(file1Location); <span class="hljs-comment">//file1Location文件的路径 ,我是在手机存储根目录下创建了一个文件夹,里面放着了一张图片; </span><br></code></pre></td></tr></table></figure>
<h5 id="设置文件的格式"><a class="markdownIt-Anchor" href="#设置文件的格式">#</a> 设置文件的格式</h5>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs cpp">RequestBody imageBody = RequestBody.<span class="hljs-built_in">create</span>(MediaType.<span class="hljs-built_in">parse</span>(<span class="hljs-string">&quot;multipart/form-data&quot;</span>), file);<br><br>   <span class="hljs-comment">//添加文件(uploadfile就是你服务器中需要的文件参数)</span><br><br>   builder.<span class="hljs-built_in">addFormDataPart</span>(<span class="hljs-string">&quot;uploadfile&quot;</span>, file.<span class="hljs-built_in">getName</span>(), imageBody); <br></code></pre></td></tr></table></figure>
<h5 id="生成接口需要的list"><a class="markdownIt-Anchor" href="#生成接口需要的list">#</a> 生成接口需要的 list</h5>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs dart"><span class="hljs-built_in">List</span>&lt;MultipartBody.Part&gt; parts = builder.build().parts(); <br></code></pre></td></tr></table></figure>
<h5 id="创建设置okhttpclient"><a class="markdownIt-Anchor" href="#创建设置okhttpclient">#</a> 创建设置 OkHttpClient</h5>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs cpp">OkHttpClient okHttpClient = <span class="hljs-keyword">new</span> OkHttpClient.<span class="hljs-built_in">Builder</span>()<br>           .<span class="hljs-built_in">connectTimeout</span>(<span class="hljs-number">20</span>, TimeUnit.SECONDS)<br>           .<span class="hljs-built_in">readTimeout</span>(<span class="hljs-number">20</span>, TimeUnit.SECONDS)<br>           .<span class="hljs-built_in">writeTimeout</span>(<span class="hljs-number">20</span>, TimeUnit.SECONDS)<br>           <span class="hljs-comment">//允许失败重试</span><br>           .<span class="hljs-built_in">retryOnConnectionFailure</span>(<span class="hljs-literal">true</span>)<br>           .<span class="hljs-built_in">build</span>(); <br></code></pre></td></tr></table></figure>
<h5 id="创建retrofit实例对象"><a class="markdownIt-Anchor" href="#创建retrofit实例对象">#</a> 创建 retrofit 实例对象</h5>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs cpp">Retrofit retrofit = <span class="hljs-keyword">new</span> Retrofit.<span class="hljs-built_in">Builder</span>()<br>           <span class="hljs-comment">//设置基站地址(基站地址+描述网络请求的接口上面注释的Post地址,就是要上传文件到服务器的地址,</span><br>           <span class="hljs-comment">// 这只是一种设置地址的方法,还有其他方式,不在赘述)</span><br>           .<span class="hljs-built_in">baseUrl</span>(<span class="hljs-string">&quot;你的基站地址&quot;</span>)<br>           <span class="hljs-comment">//设置委托,使用OKHttp联网,也可以设置其他的;</span><br>           .<span class="hljs-built_in">client</span>(okHttpClient)<br>           <span class="hljs-comment">//设置数据解析器,如果没有这个类需要添加依赖:</span><br>           .<span class="hljs-built_in">addConverterFactory</span>(GsonConverterFactory.<span class="hljs-built_in">create</span>())<br>           <span class="hljs-comment">//设置支持rxJava</span><br>           <span class="hljs-comment">// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())</span><br>           .<span class="hljs-built_in">build</span>(); <br></code></pre></td></tr></table></figure>
<h5 id="实例化请求接口把表单传递过去"><a class="markdownIt-Anchor" href="#实例化请求接口把表单传递过去">#</a> 实例化请求接口，把表单传递过去；</h5>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs java"> Call&lt;BaseBean&gt; call = retrofit.create(Api.class).upLoading(parts);<br>    <span class="hljs-comment">//开始请求</span><br>    call.enqueue(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Callback</span>&lt;BaseBean&gt;() &#123;<br><br>        <span class="hljs-meta">@Override</span><br>        <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">onResponse</span><span class="hljs-params">(Call&lt;BaseBean&gt; call, Response&lt;BaseBean&gt; response)</span> &#123;<br>            <span class="hljs-comment">//联网有响应或有返回数据</span><br>            System.out.println(response.body().toString());<br>        &#125;<br><br>        <span class="hljs-meta">@Override</span><br>        <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">onFailure</span><span class="hljs-params">(Call&lt;BaseBean&gt; call, Throwable t)</span> &#123;<br>            <span class="hljs-comment">//连接失败,多数是网络不可用导致的</span><br>            System.out.println(<span class="hljs-string">&quot;网络不可用&quot;</span>);<br>        &#125;<br>    &#125;);<br>&#125; <br></code></pre></td></tr></table></figure>
<h3 id="这就ok了单个文件上传完毕"><a class="markdownIt-Anchor" href="#这就ok了单个文件上传完毕">#</a> 这就 ok 了，单个文件上传完毕！！！</h3>
<h2 id="多文件上传以两个文件为例"><a class="markdownIt-Anchor" href="#多文件上传以两个文件为例">#</a> 多文件上传 (以两个文件为例)</h2>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs cpp">对比一个文件,这个只需要在[设置文件的格式] 这一步,多添加一个即可;<br>   RequestBody imageBody = RequestBody.<span class="hljs-built_in">create</span>(MediaType.<span class="hljs-built_in">parse</span>(<span class="hljs-string">&quot;multipart/form-data&quot;</span>), file);<br>   RequestBody imageBody1 = RequestBody.<span class="hljs-built_in">create</span>(MediaType.<span class="hljs-built_in">parse</span>(<span class="hljs-string">&quot;multipart/form-data&quot;</span>), file1);<br>   <span class="hljs-comment">//添加文件(uploadfile就是你服务器中需要的文件参数)</span><br>   builder.<span class="hljs-built_in">addFormDataPart</span>(<span class="hljs-string">&quot;uploadfile&quot;</span>, file.<span class="hljs-built_in">getName</span>(), imageBody);<br>   builder.<span class="hljs-built_in">addFormDataPart</span>(<span class="hljs-string">&quot;uploadfile1&quot;</span>, file1.<span class="hljs-built_in">getName</span>(), imageBody1); <br></code></pre></td></tr></table></figure>
<h2 id="接下来看文件下载ღ"><a class="markdownIt-Anchor" href="#接下来看文件下载ღ">#</a> 接下来看文件下载ღ</h2>
<h1 id="文件下载"><a class="markdownIt-Anchor" href="#文件下载">#</a> 文件下载:</h1>
<h2 id="首先还是要在api接口创建一个方法"><a class="markdownIt-Anchor" href="#首先还是要在api接口创建一个方法">#</a> 首先还是要在 API 接口创建一个方法；</h2>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs dart"><span class="hljs-comment"><span class="language-markdown">/**</span></span><br><span class="language-markdown"><span class="hljs-comment"><span class="hljs-bullet">*</span> 下载文件</span></span><br><span class="language-markdown"><span class="hljs-comment"><span class="hljs-bullet">*</span> 如果下载大文件的一定要加上  @Streaming  注解</span></span><br><span class="language-markdown"><span class="hljs-comment"><span class="hljs-bullet">*</span></span></span><br><span class="language-markdown"><span class="hljs-comment"><span class="hljs-bullet">*</span> @param fileUrl 文件的路径</span></span><br><span class="language-markdown"><span class="hljs-comment"><span class="hljs-bullet">*</span> @return 请求call</span></span><br><span class="language-markdown"><span class="hljs-comment"><span class="hljs-emphasis">*/</span></span></span><br><span class="hljs-meta">@GET</span><br>Call&lt;ResponseBody&gt; download(<span class="hljs-meta">@Url</span> <span class="hljs-built_in">String</span> fileUrl); <br></code></pre></td></tr></table></figure>
<h3 id="然后就是创建一个retrofit对象跟上面一样由于每次创建retrofit对象会用到很多重复的代码可以抽取成一个公共方法"><a class="markdownIt-Anchor" href="#然后就是创建一个retrofit对象跟上面一样由于每次创建retrofit对象会用到很多重复的代码可以抽取成一个公共方法">#</a> 然后就是创建一个 retrofit 对象，跟上面一样 (由于每次创建 retrofit 对象会用到很多重复的代码，可以抽取成一个公共方法)</h3>
<h2 id="实例化请求接口"><a class="markdownIt-Anchor" href="#实例化请求接口">#</a> 实例化请求接口:</h2>
<p>我在百度上找到一张图片，把他的地址拆分了一下，最后一个斜杠之前的 url 设置为了 baseUrl, 斜杠之后设置在这里；</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><code class="hljs kotlin">地址拆分:    .baseUrl(<span class="hljs-string">&quot;https://gss3.bdstatic.com/-Po3dSag_xI4khGkpoWK1HF6hhy/baike/w%3D268%3Bg%3D0/sign=e3dc64d05a3d26972ed30f5b6dc0d5c6/&quot;</span>)<br><br> <span class="hljs-comment">//整体地址https://gss3.bdstatic.com/Po3dSag_xI4khGkpoWK1HF6hhy/baike/w%3D268%3Bg%3D0/sign=e3dc64d05a3d26972ed30f5b6dc0d5c6/(在这里拆分了)241f95cad1c8a7868a2713146c09c93d70cf509e.jpg</span><br><br>   Call&lt;ResponseBody&gt; download = retrofit.create(Api.<span class="hljs-keyword">class</span>).download(<span class="hljs-string">&quot;241f95cad1c8a7868a2713146c09c93d70cf509e.jpg&quot;</span>);<br>   download.enqueue(new Callback&lt;ResponseBody&gt;() &#123;<br><br>       <span class="hljs-meta">@Override</span><br>       <span class="hljs-keyword">public</span> void onResponse(Call&lt;ResponseBody&gt; call, Response&lt;ResponseBody&gt; response) &#123;<br>           <span class="hljs-keyword">if</span> (response != <span class="hljs-literal">null</span> &amp;&amp; response.isSuccessful()) &#123;<br>           <span class="hljs-comment">// writeResponseBodyToDisk 是我写的下载保存本地工具类,可以参考一下</span><br>               boolean toDisk = writeResponseBodyToDisk(response.body());<br>               <span class="hljs-keyword">if</span> (toDisk) &#123;<br>                   System.<span class="hljs-keyword">out</span>.println(<span class="hljs-string">&quot;下载成功请查看&quot;</span>);<br>               &#125; <span class="hljs-keyword">else</span> &#123;<br>                   System.<span class="hljs-keyword">out</span>.println(<span class="hljs-string">&quot;下载失败,请稍后重试&quot;</span>);<br>               &#125;<br>           &#125; <span class="hljs-keyword">else</span> &#123;<br>               System.<span class="hljs-keyword">out</span>.println(<span class="hljs-string">&quot;服务器返回错误&quot;</span>);<br>           &#125;<br>       &#125;<br><br>       <span class="hljs-meta">@Override</span><br>       <span class="hljs-keyword">public</span> void onFailure(Call&lt;ResponseBody&gt; call, Throwable t) &#123;<br>           <span class="hljs-comment">//连接失败,多数是网络不可用导致的</span><br>           System.<span class="hljs-keyword">out</span>.println(<span class="hljs-string">&quot;网络不可用&quot;</span>);<br>       &#125;<br>   &#125;); <br></code></pre></td></tr></table></figure>
<h2 id="writeresponsebodytodisk下载文件保存到本地工具类"><a class="markdownIt-Anchor" href="#writeresponsebodytodisk下载文件保存到本地工具类">#</a> writeResponseBodyToDisk (下载文件保存到本地工具类)</h2>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">* 下载到本地</span><br><span class="hljs-comment">*</span><br><span class="hljs-comment">* <span class="hljs-doctag">@param</span> body 内容</span><br><span class="hljs-comment">* <span class="hljs-doctag">@return</span> 成功或者失败</span><br><span class="hljs-comment">*/</span><br><span class="hljs-keyword">private</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">writeResponseBodyToDisk</span><span class="hljs-params">(ResponseBody body)</span> &#123;<br>    <span class="hljs-keyword">try</span> &#123;<br>        <span class="hljs-comment">//判断文件夹是否存在</span><br>        <span class="hljs-type">File</span> <span class="hljs-variable">files</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">File</span>(SD_HOME_DIR);<span class="hljs-comment">//跟目录一个文件夹</span><br>        <span class="hljs-keyword">if</span> (!files.exists()) &#123;<br>            <span class="hljs-comment">//不存在就创建出来</span><br>            files.mkdirs();<br>        &#125;<br>        <span class="hljs-comment">//创建一个文件</span><br>        <span class="hljs-type">File</span> <span class="hljs-variable">futureStudioIconFile</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">File</span>(SD_HOME_DIR + <span class="hljs-string">&quot;download.jpg&quot;</span>);<br>        <span class="hljs-comment">//初始化输入流</span><br>        <span class="hljs-type">InputStream</span> <span class="hljs-variable">inputStream</span> <span class="hljs-operator">=</span> <span class="hljs-literal">null</span>;<br>        <span class="hljs-comment">//初始化输出流</span><br>        <span class="hljs-type">OutputStream</span> <span class="hljs-variable">outputStream</span> <span class="hljs-operator">=</span> <span class="hljs-literal">null</span>;<br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-comment">//设置每次读写的字节</span><br>            <span class="hljs-type">byte</span>[] fileReader = <span class="hljs-keyword">new</span> <span class="hljs-title class_">byte</span>[<span class="hljs-number">4096</span>];<br>            <span class="hljs-type">long</span> <span class="hljs-variable">fileSize</span> <span class="hljs-operator">=</span> body.contentLength();<br>            <span class="hljs-type">long</span> <span class="hljs-variable">fileSizeDownloaded</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;<br>            <span class="hljs-comment">//请求返回的字节流</span><br>            inputStream = body.byteStream();<br>            <span class="hljs-comment">//创建输出流</span><br>            outputStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">FileOutputStream</span>(futureStudioIconFile);<br>            <span class="hljs-comment">//进行读取操作</span><br>            <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) &#123;<br>                <span class="hljs-type">int</span> <span class="hljs-variable">read</span> <span class="hljs-operator">=</span> inputStream.read(fileReader);<br>                <span class="hljs-keyword">if</span> (read == -<span class="hljs-number">1</span>) &#123;<br>                    <span class="hljs-keyword">break</span>;<br>                &#125;<br>                <span class="hljs-comment">//进行写入操作</span><br>                outputStream.write(fileReader, <span class="hljs-number">0</span>, read);<br>                fileSizeDownloaded += read;<br>            &#125;<br><br>            <span class="hljs-comment">//刷新</span><br>            outputStream.flush();<br>            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;<br>        &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>        &#125; <span class="hljs-keyword">finally</span> &#123;<br>            <span class="hljs-keyword">if</span> (inputStream != <span class="hljs-literal">null</span>) &#123;<br>                <span class="hljs-comment">//关闭输入流</span><br>                inputStream.close();<br>            &#125;<br>            <span class="hljs-keyword">if</span> (outputStream != <span class="hljs-literal">null</span>) &#123;<br>                <span class="hljs-comment">//关闭输出流</span><br>                outputStream.close();<br>            &#125;<br>        &#125;<br>    &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>    &#125;<br>&#125; <br></code></pre></td></tr></table></figure>
                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
  
</div>


              

              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2024/02/18/android/Gson%E5%8F%8D%E5%BA%8F%E5%88%97%E5%8C%96%E6%97%B6%E9%97%B4long%E5%80%BC%E8%BD%AC%E4%B8%BADate%E7%B1%BB%E5%9E%8B%E6%8A%A5%E9%94%99/" title="Gson反序列化时间long值转为Date类型报错">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Gson反序列化时间long值转为Date类型报错</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2024/02/18/android/RxJava/" title="RxJava">
                        <span class="hidden-mobile">RxJava</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
    <!-- 备案信息 ICP for China -->
    <div class="beian">
  <span>
    <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
      皖ICP备2023001508号
    </a>
  </span>
  
</div>

  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.4/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.20.1/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
